﻿using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using Exhort.Aop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exhort.Resolver
{
    /// <summary>
    /// 代理注册机
    /// </summary>
    public partial class ProxyRegistration : IRegistration
    {
        /// <summary>
        /// 执行注册
        /// </summary>
        /// <param name="kernel"></param>
        public void Register(IKernelInternal kernel)
        {
            RegisterInterceptor(kernel);
            RegisterCustomTargets(kernel);
            RegisterGenerateTargets(kernel);
        }

        /// <summary>
        /// 注册拦截器
        /// </summary>
        /// <param name="kernel"></param>
        private void RegisterInterceptor(IKernelInternal kernel)
        {
            kernel.Register(Component.For<Interceptor>().ImplementedBy<Interceptor>());
        }

        /// <summary>
        /// 预留注册自定义服务
        /// </summary>
        /// <param name="kernel"></param>
        private void RegisterCustomTargets(IKernelInternal kernel)
        {

        }

        /// <summary>
        /// 标准服务注册集
        /// </summary>
        private List<IRegistration> registerGenerateList = new List<IRegistration>();

        /// <summary>
        /// 注册标准服务
        /// </summary>
        /// <param name="kernel"></param>
        private void RegisterGenerateTargets(IKernelInternal kernel)
        {
            registerGenerateList.ForEach(m => { kernel.Register(m); });
        }

        /// <summary>
        /// 拦截器引用
        /// </summary>
        private InterceptorReference interceptorReference = InterceptorReference.ForType<Interceptor>();

        /// <summary>
        /// 标准服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TImpl"></typeparam>
        /// <returns></returns>
        private IRegistration GetTargetRegistration<T, TImpl>() where TImpl : T where T : class
        {
            return Component.For<T>().ImplementedBy<TImpl>().LifestyleTransient().Interceptors(interceptorReference).Anywhere;
        }
    }
}